// check-practice.js
import { editProfile,logout, setupUserProfile } from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
export async function displayAnswers() {
    try {
        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        const practiceId = urlParams.get('practiceId');
        const username = urlParams.get('username');
        const userId = urlParams.get('userId');
        await setupUserProfile(username);
        if (!practiceId || !userId) {
            throw new Error('缺少必要的参数');
        }

        // 获取练习详情
        const practiceDetail = await fetchPracticeDetail(practiceId, userId);
        document.getElementById('practice-title').textContent = practiceDetail.practice_name;
        document.getElementById('course-info').textContent = `所属课程：${escapeHTML(practiceDetail.course_name)}`;

        // 获取练习评阅状态
        const isJudged = await fetchPracticeJudgmentStatus(practiceId, userId);
        
        // 获取用户分数和总分
        const userScore = await fetchUserScore(practiceId, userId);
        const totalScore = await fetchPracticeScore(practiceId);

        document.getElementById('user-score').textContent = `${escapeHTML(userScore.totalScore)}/${escapeHTML(totalScore.data.total_score)}`;

        // 获取题目答案
        const questionsContainer = document.getElementById('questions-container');
        questionsContainer.innerHTML = '';

        // 获取并显示选择题答案
        const choiceQuestions = await fetchChoiceQuestions(practiceId, userId);
        displayChoiceQuestions(choiceQuestions, questionsContainer);

        const fillQuestions = await fetchFillQuestions(practiceId, userId);
        displayFillQuestions(fillQuestions, questionsContainer);

        const essayQuestions = await fetchEssayQuestions(practiceId, userId);
        displayEssayQuestions(essayQuestions, questionsContainer, isJudged); // 传递评阅状态

        // 添加返回按钮事件
        document.getElementById('back-btn').addEventListener('click', () => {
            window.location.href = `grade-practice.html?username=${escapeHTML(username)}`;
        });

        // 处理完成评阅按钮
        const completeJudgmentBtn = document.getElementById('complete-judgment-btn');
        
        // 根据评阅状态设置按钮状态
        if (isJudged) {
            completeJudgmentBtn.textContent = '已完成评阅';
            completeJudgmentBtn.disabled = true;
            completeJudgmentBtn.classList.add('opacity-50', 'cursor-not-allowed');
            
            // 禁用所有解答题的分数输入框
            document.querySelectorAll('.essay-score-input').forEach(input => {
                input.disabled = true;
                input.classList.add('bg-gray-100', 'cursor-not-allowed');
            });
        } else {
            // 未评阅状态，添加点击事件
            completeJudgmentBtn.addEventListener('click', async () => {
                try {
                    // 收集所有解答题的分数更新
                    const essayQuestionCards = document.querySelectorAll('.essay-question');
                    const updatePromises = Array.from(essayQuestionCards).map(async (card) => {
                        const questionNumber = parseInt(card.dataset.questionNumber); // 转换为整数
                        const scoreInput = card.querySelector('.essay-score-input');
                        const newScore = parseInt(scoreInput.value);
                        
                        // 验证分数是否在有效范围内
                        const maxScore = parseInt(scoreInput.max);
                        if (isNaN(newScore) || newScore < 0 || newScore > maxScore) {
                            throw new Error(`题目 ${escapeHTML(questionNumber)} 的分数无效，请输入0-${escapeHTML(maxScore)}之间的数字`);
                        }
                        //console.log(userId, practiceId, questionNumber, newScore);
                        const questionOrder = questionNumber - 1;
                        return updateEssayScore(userId, practiceId, questionOrder, newScore);
                    });
                    
                    // 等待所有分数更新完成
                    await Promise.all(updatePromises);
                    
                    // 刷新总分显示
                    const updatedUserScore = await fetchUserScore(practiceId, userId);
                    document.getElementById('user-score').textContent = `${escapeHTML(updatedUserScore.totalScore)}/${escapeHTML(totalScore.data.total_score)}`;
                    
                    alert('评阅完成');
                    completeJudgmentBtn.textContent = '已完成评阅';
                    completeJudgmentBtn.disabled = true;
                    completeJudgmentBtn.classList.add('opacity-50', 'cursor-not-allowed');
                    
                    // 禁用所有解答题的分数输入框
                    document.querySelectorAll('.essay-score-input').forEach(input => {
                        input.disabled = true;
                        input.classList.add('bg-gray-100', 'cursor-not-allowed');
                    });
                } catch (error) {
                    console.error('评阅过程中出错:', error);
                    alert(`评阅失败: ${escapeHTML(error.message)}`);
                }
            });
        }
    } catch (error) {
        console.error('加载答案失败:', error);
        alert(`加载答案失败: ${escapeHTML(error.message)}`);
    }
}

// 获取练习详情
export async function fetchPracticeDetail(practiceId, userId) {
    const response = await fetch(`/practice/detail/${escapeHTML(practiceId)}?userId=${escapeHTML(userId)}`);
    const practice = await response.json();

    // 获取课程信息
    const courseResponse = await fetch(`/get-course/${escapeHTML(practice.course_code)}`);
    const course = await courseResponse.json();

    return { ...practice, course_name: course.course_name };
}

export async function fetchUserScore(practiceId, userId) {
    const response = await fetch(`/calculate-total-score?userId=${escapeHTML(userId)}&practiceId=${escapeHTML(practiceId)}`);
    return await response.json();
}

export async function fetchPracticeScore(practiceId) {
    const response = await fetch(`/api/practice/${escapeHTML(practiceId)}/total-score`);
    return await response.json();
}

export async function fetchChoiceQuestions(practiceId, userId) {
    const response = await fetch(`/api/choice-questions/${escapeHTML(practiceId)}?userId=${escapeHTML(userId)}`);
    return await response.json();
}

export async function fetchFillQuestions(practiceId, userId) {
    const response = await fetch(`/api/fill-questions/${escapeHTML(practiceId)}?userId=${escapeHTML(userId)}`);
    return await response.json();
}

export async function fetchEssayQuestions(practiceId, userId) {
    const response = await fetch(`/api/essay-questions/${escapeHTML(practiceId)}?userId=${escapeHTML(userId)}`);
    return await response.json();
}

// 显示选择题
export function displayChoiceQuestions(questions, container) {
    questions.forEach((question, index) => {
        const questionCard = document.createElement('div');
        questionCard.className = 'bg-white rounded-xl p-6 shadow-md border border-blue-100 mb-6';

        const options = ['A', 'B', 'C', 'D'];
        let optionsHtml = options.map(option => {
            const isCorrect = question.correct_answer === option;
            const isSelected = question.user_answer === option;
            
            let statusClass = 'bg-gray-50';
            let statusIcon = '<span class="w-5 h-5 flex items-center justify-center bg-gray-200 rounded-full mr-2"></span>';
            let statusText = '';
            
            if (isCorrect) {
                statusClass = 'bg-green-50 border border-green-100';
                statusIcon = '<span class="w-5 h-5 flex items-center justify-center bg-green-500 text-white rounded-full mr-2"><i class="fas fa-check text-xs"></i></span>';
                statusText = isSelected ? 
                    '<span class="text-green-600 text-sm ml-2"><i class="fas fa-check-circle mr-1"></i>回答正确</span>' : 
                    '<span class="text-green-600 text-sm ml-2"><i class="fas fa-check-circle mr-1"></i>正确答案</span>';
            } else if (isSelected) {
                statusClass = 'bg-red-50 border border-red-100';
                statusIcon = '<span class="w-5 h-5 flex items-center justify-center bg-red-500 text-white rounded-full mr-2"><i class="fas fa-times text-xs"></i></span>';
                statusText = '<span class="text-red-600 text-sm ml-2"><i class="fas fa-times-circle mr-1"></i>回答错误</span>';
            }

            return `
            <div class="${statusClass} p-3 rounded-lg mb-3 flex items-start transition-all">
                ${statusIcon}
                <div>
                    <div class="flex items-baseline">
                        <span class="font-medium text-blue-800 mr-2">${option}.</span>
                        <span>${question[`option_${escapeHTML(option.toLowerCase())}`]}</span>
                    </div>
                    ${statusText}
                </div>
            </div>`;
        }).join('');

        questionCard.innerHTML = `
        <div class="flex justify-between items-start mb-4">
            <h4 class="text-lg font-bold text-blue-800">${escapeHTML(index + 1)}. ${escapeHTML(question.question)}</h4>
            <span class="bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm font-medium">${escapeHTML(question.score)}分</span>
        </div>
        <div class="mb-4">
            ${optionsHtml}
        </div>
        <div class="flex justify-between items-center pt-4 border-t border-blue-100">
            <span class="text-blue-600 font-medium">本题得分</span>
            <span class="text-xl font-bold ${escapeHTML(question.user_score) !== null ? 'text-blue-700' : 'text-gray-400'}">
                ${escapeHTML(question.user_score !== null ? question.user_score : '待批阅')}
            </span>
        </div>`;

        container.appendChild(questionCard);
    });
}

// 显示填空题
export function displayFillQuestions(questions, container) {
    questions.forEach((question, index) => {
        const questionCard = document.createElement('div');
        questionCard.className = 'bg-white rounded-xl p-6 shadow-md border border-blue-100 mb-6';

        let blankCount = 0;
        const questionText = question.question.replace(/__/g, () => {
            blankCount++;
            return `<span class="inline-block mx-1 px-2 py-1 bg-blue-100 text-blue-700 rounded">空${escapeHTML(blankCount)}</span>`;
        });

        let blanksHtml = '';
        for (let i = 1; i <= blankCount; i++) {
            const correctAnswer = question[`blank${escapeHTML(i)}_answer`];
            const userAnswer = question[`commited_answer${escapeHTML(i)}`];
            const isCorrect = userAnswer === correctAnswer;
            const hasAnswer = userAnswer !== undefined && userAnswer !== null;

            let statusClass = 'bg-gray-50';
            let statusIcon = '<span class="w-5 h-5 flex items-center justify-center bg-gray-200 rounded-full mr-2"></span>';
            let statusText = '';
            
            if (hasAnswer) {
                if (isCorrect) {
                    statusClass = 'bg-green-50 border border-green-100';
                    statusIcon = '<span class="w-5 h-5 flex items-center justify-center bg-green-500 text-white rounded-full mr-2"><i class="fas fa-check text-xs"></i></span>';
                    statusText = '<span class="text-green-600 text-sm ml-2"><i class="fas fa-check-circle mr-1"></i>回答正确</span>';
                } else {
                    statusClass = 'bg-red-50 border border-red-100';
                    statusIcon = '<span class="w-5 h-5 flex items-center justify-center bg-red-500 text-white rounded-full mr-2"><i class="fas fa-times text-xs"></i></span>';
                    statusText = `<span class="text-red-600 text-sm ml-2"><i class="fas fa-times-circle mr-1"></i>回答错误 (正确答案: ${escapeHTML(correctAnswer)})</span>`;
                }
            }

            blanksHtml += `
            <div class="${statusClass} p-3 rounded-lg mb-3 transition-all">
                <div class="flex items-start">
                    ${statusIcon}
                    <div>
                        <div class="flex items-baseline">
                            <span class="font-medium text-blue-800 mr-2">空${escapeHTML(i)}:</span>
                            <span>${escapeHTML(hasAnswer ? userAnswer : '未填写')}</span>
                        </div>
                        ${statusText}
                    </div>
                </div>
            </div>`;
        }

        questionCard.innerHTML = `
        <div class="flex justify-between items-start mb-4">
            <h4 class="text-lg font-bold text-blue-800">${escapeHTML(index + 1)}. ${questionText}</h4>
            <span class="bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm font-medium">${escapeHTML(question.score)}分</span>
        </div>
        <div class="mb-4">
            ${blanksHtml}
        </div>
        <div class="flex justify-between items-center pt-4 border-t border-blue-100">
            <span class="text-blue-600 font-medium">本题得分</span>
            <span class="text-xl font-bold ${escapeHTML(question.score) !== null ? 'text-blue-700' : 'text-gray-400'}">
                ${escapeHTML(question.score !== null ? question.score : '待批阅')}
            </span>
        </div>`;

        container.appendChild(questionCard);
    });
}

// 显示解答题
export function displayEssayQuestions(questions, container, isJudged) {
    questions.forEach((question, index) => {
        const questionCard = document.createElement('div');
        questionCard.className = 'bg-white rounded-xl p-6 shadow-md border border-blue-100 mb-6 essay-question';
        questionCard.dataset.questionNumber = question.question_order + 1;

        const disabledClass = isJudged ? 'bg-gray-100 cursor-not-allowed' : '';
        const disabledAttr = isJudged ? 'disabled' : '';

        questionCard.innerHTML = `
        <div class="flex justify-between items-start mb-4">
            <h4 class="text-lg font-bold text-blue-800">${escapeHTML(index) + 1}. ${escapeHTML(question.question)}</h4>
            <span class="bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm font-medium">${escapeHTML(question.score)}分</span>
        </div>
        <div class="mb-6 p-4 bg-gray-50 border border-gray-200 rounded-lg">
            <h5 class="text-sm font-medium text-blue-600 mb-2">学生答案</h5>
            <div class="text-gray-800 whitespace-pre-line">${escapeHTML(question.user_answer || '未填写')}</div>
        </div>
        <div class="flex justify-between items-center pt-4 border-t border-blue-100">
            <span class="text-blue-600 font-medium">本题得分</span>
            <div class="flex items-center gap-2">
                <input type="number" 
                    class="essay-score-input w-24 px-3 py-2 border border-blue-200 rounded-lg focus:ring-2 focus:ring-blue-200 focus:border-blue-400 ${escapeHTML(disabledClass)}" 
                    min="0" max="${escapeHTML(question.score)}" 
                    value="${escapeHTML(question.user_score) || 0}" 
                    ${escapeHTML(disabledAttr)}>
                <span class="text-gray-500">/ ${escapeHTML(question.score)}</span>
            </div>
        </div>`;

        container.appendChild(questionCard);
    });
}

// 更新解答题得分的接口
export async function updateEssayScore(userId, practiceId,questionOrder, newScore) {
    try {
        //console.log('updateEssayScore', userId, practiceId, questionOrder, newScore);
        const response = await fetch(`/update-essay-score`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId,
                practiceId,
                questionOrder,  // 确保传递的是正确的题号
                newScore
            })
        });

        if (!response.ok) {
            throw new Error(`更新解答题得分失败: ${escapeHTML(response.statusText)}`);
        }

        const data = await response.json();
        if (!data.success) {
            throw new Error(data.message || '更新失败');
        }
        
        return data;
    } catch (error) {
        console.error('更新解答题得分错误:', error);
        throw error;  // 抛出错误以便上层处理
    }
}

// 页面加载完成后显示答案
window.onload = displayAnswers;

// 获取练习评阅状态
export async function fetchPracticeJudgmentStatus(practiceId, userId) {
    try {
        const response = await fetch(`/api/commited-practice/${escapeHTML(practiceId)}`);
        if (!response.ok) {
            throw new Error('获取练习评阅状态失败');
        }
        
        const submissions = await response.json();
        // 找到当前用户的提交记录
        const userSubmission = submissions.find(sub => sub.user_id === userId);
        
        if (!userSubmission) {
            throw new Error('未找到用户提交记录');
        }
        
        return userSubmission.is_judged;
    } catch (error) {
        console.error('获取评阅状态错误:', error);
        return false; // 出错时默认未评阅
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault();
            const urlParams = new URLSearchParams(window.location.search);
            const username = urlParams.get('username'); 
            window.location.href = `grade-practice.html?username=${escapeHTML(username)}`;
        });
    }
});

export function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    return str.replace(/[&<>"']/g, function (match) {
    switch (match) {
    case '&':
    return '&amp;';
    case '<':
    return '&lt;';
    case '>':
    return '&gt;';
    case '"':
    return '&quot;';
    case "'":
    return '&#039;';
}
 });
}